package org.example.Polls;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainMenuActivity extends Activity implements OnClickListener {
	// constants for return results
	private static final int CREATE_POLL_RESULT = 1;
	
	// constants for dialogs
	private static final int REGISTER_NOW_DIALOG = 1;
	private static final int ABOUT_DIALOG = 2;
	
	// other constants
	private static final String TAG = "MainMenuActivity";
	public static String CONFIG_FILE = "appConfig.properties";
	
	private Properties properties = new Properties();
	
	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        TextView mainMenuView = (TextView)findViewById(R.id.main_menu_text_view);
        registerForContextMenu(mainMenuView);
        
        View create_poll = findViewById(R.id.main_menu_create_poll_button);
        View view_polls = findViewById(R.id.main_menu_view_polls_button);
        
        create_poll.setOnClickListener(this);
        view_polls.setOnClickListener(this);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_options, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// Handle item selection
    	switch(item.getItemId()) {
    	case R.id.main_menu_options_settings:
    		startActivity(new Intent(this, SettingsActivity.class));
    		return true;
    	case R.id.main_menu_options_about:
    		showDialog(ABOUT_DIALOG);
    		return true;
    	default:
    		return super.onOptionsItemSelected(item);
    	}
    }
    
    @Override
    protected Dialog onCreateDialog(int dialogId) {
    	Dialog dialog = null;
    	AlertDialog.Builder builder = null;
    	switch (dialogId) {
    	case REGISTER_NOW_DIALOG:
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage("You must register before using this application.  Do you want to register now?")
    		       .setCancelable(false)
    		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    		    	   public void onClick(DialogInterface dialog, int id) {
    		    		   startActivity(new Intent(MainMenuActivity.this, RegisterActivity.class));
    		    		   dismissDialog(REGISTER_NOW_DIALOG);
    		    	   }
    		       })
            	   .setNegativeButton("No", new DialogInterface.OnClickListener() {
            			public void onClick(DialogInterface dialog, int id) {
            				MainMenuActivity.this.finish();
            			}
            	   });
    		dialog = builder.create();
    		break;
    	case ABOUT_DIALOG:
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage("uVote\nA collaborative voting application\nUniversity of Colorado, Boulder\nCSCI-5448\nBrent Smith, Jake Smith, Copyright 2011")
    		       .setCancelable(false)
    		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    		    	   public void onClick(DialogInterface dialog, int id) {
    		    		   dismissDialog(ABOUT_DIALOG);
    		    	   }
    		       });
    		dialog = builder.create();
    		break;
    	}
    	return dialog;
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	Log.d(TAG, "Resuming MainMenuActivity");
        if(!isUserRegistered()) {
        	Log.d(TAG, "User is not registered");
        	Log.d(TAG, "Calling showDialog(REGISTER_NOW_DIALOG)");
        	showDialog(REGISTER_NOW_DIALOG);
        	Log.d(TAG, "Finished showDialog(REGISTER_NOW_DIALOG)");
        } else {
        	/** Check shared preferences */
    		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    		String username = prefs.getString("username", null);
    		String password = prefs.getString("password", null);
    		if (username == null || password == null)
    			throw new RuntimeException("username/password properties are missing");
    		Log.i(TAG, "Username found: "+username);
    		Log.i(TAG, "Password found: "+password);
    		
            RequestContext ctxt = RequestContext.getContext();
            ctxt.setUsername(username);
            ctxt.setPassword(password);
        }
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	Log.d(TAG, "Pausing MainMenuActivity");
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult: requestCode="+requestCode+" resultCode="+resultCode);
		switch (requestCode) {
    		case CREATE_POLL_RESULT:
        		if (resultCode != RESULT_OK)
        			return;
    			Long pollId = data.getExtras().getLong(CreatePollActivity.CREATE_POLL_EXTRA);
    			Intent intent = new Intent(this, ViewPollDetailsActivity.class);
    			intent.putExtra(ViewPollDetailsActivity.POLL_ID_EXTRA, pollId);
    			startActivity(intent);
    			break;
    		default:
    			Log.w(TAG, "Unknown resultCode");
		}
	}

	public void onClick(View v) {
    	switch(v.getId()) {
    	case R.id.main_menu_create_poll_button:
    		Intent intent = new Intent(this, CreatePollActivity.class);
    		startActivityForResult(intent, CREATE_POLL_RESULT);
    		break;
    	case R.id.main_menu_view_polls_button:
    		startActivity(new Intent(this, ViewPollsActivity.class));
    		break;
    	}
    }
    
    private void readConfiguration() throws IOException {
		InputStream s = openFileInput(CONFIG_FILE);
		properties.load(s);
    }
    
    private boolean isUserRegistered() {
    	/** Check internal storage */
        try {
			readConfiguration();
		} catch(IOException e) {
			Log.d(TAG, "unable to read configuration");
			return false;
		}
        if(properties.getProperty("userName") == null) {
        	return false;
        } else if(properties.getProperty("password") == null) {
        	return false;
        }
        return true;
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_context, menu);
    	DefaultServiceFactory factory = DefaultServiceFactory.getInstance();
    	if (DefaultServiceFactory.MOCK_IMPLEMENTATION.equals(factory.getServiceFactoryImpl())) {
    		Log.i(TAG, "Current service factory is MockServiceFactory");
    		menu.getItem(0).setChecked(true);
    	} else if (DefaultServiceFactory.SOAP_IMPLEMENTATION.equals(factory.getServiceFactoryImpl())) {
    		Log.i(TAG, "Current service factory is SOAPServiceFactory");
    		menu.getItem(1).setChecked(true);
    	}
    }

    public boolean onContextItemSelected(MenuItem item) {
    	//AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	DefaultServiceFactory factory = DefaultServiceFactory.getInstance();
    	switch (item.getItemId()) {
    	case R.id.mock_item:
    		Log.i(TAG, "Switching to MockServiceFactory");
    		factory.setServiceFactoryImpl(DefaultServiceFactory.MOCK_IMPLEMENTATION);
    		item.setChecked(true);
    		return true;
    	case R.id.soap_item:
    		Log.i(TAG, "Switching to SOAPServiceFactory");
    		factory.setServiceFactoryImpl(DefaultServiceFactory.SOAP_IMPLEMENTATION);
    		item.setChecked(true);
    		return true;
    	default:
    		return super.onContextItemSelected(item);
    	}
    }

}
